﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Files;
namespace LWrap.IndexSync
{
    public class DifferentialSync : IndexFileSyncBase
    {
        public FileSyncScopeFilter SyncScopeFilter { get; set; }
        public FileSyncOptions SyncOptions { get; set; }

        public DifferentialSync()
        {
            //FileSyncScopeFilter tmpScopFltr= new FileSyncScopeFilter();

            FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges |
                        FileSyncOptions.RecycleDeletedFiles |
                        FileSyncOptions.RecyclePreviousFileOnUpdates |
                        FileSyncOptions.CompareFileStreams |
                        FileSyncOptions.RecycleConflictLoserFiles;
            this.SyncOptions = options;
        }
        private void DetectChangesOnFileSystemReplica(string replicaRootPath,FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(replicaRootPath, filter, options);
                provider.DetectChanges();
            }
            finally
            {
                // Release resources
                if (provider != null)
                    provider.Dispose();
            }
        }
        public override void SyncFiles(string rootFilePath, string destinationFilePath)
        {
            FileSyncProvider sourceProvider=null;
            FileSyncProvider destinationProvider=null;
            try
            {
                this.DetectChangesOnFileSystemReplica(rootFilePath, null, this.SyncOptions);
                this.DetectChangesOnFileSystemReplica(destinationFilePath, null, this.SyncOptions);

                sourceProvider = new FileSyncProvider(rootFilePath, null, this.SyncOptions);
                destinationProvider = new FileSyncProvider(destinationFilePath, null, this.SyncOptions);
                SyncOrchestrator agent = new SyncOrchestrator();
                agent.LocalProvider = sourceProvider;
                agent.RemoteProvider = destinationProvider;
                agent.Direction = SyncDirectionOrder.Upload;
                agent.Synchronize();
            }   
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                // Release resources
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destinationProvider != null) destinationProvider.Dispose();
            }

        }
    }
}
